
import { ajax } from '../../utils/util.js'
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
let app = getApp().globalData;
let audioIcon = app.fileUrl + '95e625c7565c03247bb383de53047ce8_180_180.jpeg';
let playIcon = app.fileUrl + '248fdd4383905e05ee65f891fce5e36c_100_100.jpeg';
const device = wx.getSystemInfoSync()
const W = device.windowWidth
const H = device.windowHeight - 50
let cropper = require('../../widget/welCropper/welCropper.js');
const audioOptions = {
  duration: 10000,
  sampleRate: 44100,
  numberOfChannels: 1,
  encodeBitRate: 192000,
  format: 'aac'
}
Page({
  data: {
    audioIcon,
    playIcon,
    arrowSrc: 'https://bpic.588ku.com/element_pic/00/96/10/4456f2f6f075d88.jpg!/fw/254/quality/90/unsharp/true/compress/true',
    grades: ['甜美', '少年', '烟嗓', '知性', '清澈', '嗲嗲', '娇媚'],
    grade: '',
    imgSrc: '',
    audioSrc: '',
    setskillIntroduce: '',
    skillIntroduceFlag: 1,
    skill: {},
    soundRecordShow: false,//弹出层的显示隐藏
    secondNum: 0,
    imgIsSuccess: false,
    audioIsSuccess: false,
    tempFilePath: '',
    errorTip: '请填写技能说明'
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    // 初始化组件数据和绑定事件
    cropper.init.apply(that, [W, H]);
    console.log(this.data.cropperData)
    let skill = JSON.parse(options.skill);
    this.setData({ skill })
    //设置标题
    wx.setNavigationBarTitle({
      title: '心理咨询'
    })
    // if (!app.scopeRecord) {
    //   wx.openSetting({
    //     success () {
    //       app.scopeRecord = true;
    //     }
    //   });
    // }
  },
  getScopeRecord () {
    wx.getSetting({
      success (res) {
        console.log(res);
        if (!res.authSetting['scope.record']) {
          wx.authorize({
            scope: 'scope.record',
            success () {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              wx.startRecord()
            }
          })
        }
      }
    })
  },
  selectTap () {
    var self = this
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success (res) {
        const tempFilePaths = res.tempFilePaths[0]
        console.log(tempFilePaths)
        // 将选取图片传入cropper，并显示cropper
        // mode=rectangle 返回图片path
        // mode=quadrangle 返回4个点的坐标，并不返回图片。这个模式需要配合后台使用，用于perspective correction
        let modes = ["rectangle", "quadrangle"]
        let mode = modes[0]   //rectangle, quadrangle
        self.showCropper({
          src: tempFilePaths,
          mode: mode,
          sizeType: ['original', 'compressed'],   //'original'(default) | 'compressed'
          callback: (res) => {
            if (mode == 'rectangle') {
              console.log("crop callback:" + res)
              wx.getImageInfo({
                src: res,
                success (imgInfo) {
                  wx.uploadFile({
                    url: 'http://api.tanwancat.com/file/uploadimage',
                    filePath: imgInfo.path,
                    header: { "Content-Type": "multipart/form-data" },
                    name: 'file',
                    formData: {
                      token: wx.getStorageSync('Cookie')
                    },
                    suceess: function (res) {
                      self.setData({ imgSrc: app.fileUrl + res.data, imgIsSuccess: true })
                      console.log(11111, self.data.imgIsSuccess)
                      wx.showToast({
                        title: '上传成功',
                        icon: 'success',
                        mask: true,
                        duration: 1500
                      })
                    },
                    fail: function (err) {
                      console.log(err);
                      wx.showToast({
                        title: '上传失败',
                        icon: 'loading',
                        mask: true,
                        duration: 1000
                      })
                    },
                    complete: function (res) {
                      let data = JSON.parse(res.data);
                      if (data.code == 0) {
                        console.log(self);
                        self.setData({ imgSrc: app.fileUrl + data.data, imgIsSuccess: true });
                        wx.showToast({
                          title: '上传成功',
                          icon: 'success',
                          mask: true,
                          duration: 1000,
                          success: function () {
                            self.hideCropper()
                          }
                        })
                      }
                    }
                  })
                }
              })
            }
          }
        })
      }
    })
  },
  bindPickerChange (e) {
    let index = e.detail.value;
    let grade = this.data.grades.find((item, ind) => ind == index);
    this.setData({ grade });
  },
  setskillIntroduce (e) {
    this.setData({
      skillIntroduceFlag: 1,
      setskillIntroduce: e.detail.value
    })
  },
  //查看图片 
  previewImage () {
    wx.previewImage({
      current: this.data.imgSrc,
      urls: [this.data.imgSrc] // 
    })
  },
  //关闭录音弹出层
  closeSoundRecord () {
    this.setData({
      soundRecordShow: false,
    })
  },
  //测试长按语音
  Record () {
    recorderManager.start(audioOptions);
    recorderManager.onStart(() => {
      console.log('recorder start')
    })
    recorderManager.onError((res) => {
      console.log(res);
    })
    let secondNum = this.data.secondNum;
    //自定义属性接收定时器的返回值 用来清除
    this.recordTime = setInterval(() => {
      secondNum++;
      this.setData({
        secondNum
      })
    }, 1000);

  },
  //测试长按语音抬起
  RecordUp () {
    let self = this;
    //手抬起清楚定时器
    clearInterval(this.recordTime);
    recorderManager.stop();
    recorderManager.onStop((res) => {
      self.setData({ tempFilePath: res.tempFilePath })
      console.log('停止录音', res.tempFilePath)
    })
  },
  //上传语音
  uploadAudio () {
    let self = this;
    if (this.data.secondNum == 0) {
      wx.showToast({
        icon: 'none',
        title: '请录制语音'
      })
      self.setData({ audioIsSuccess: false });
      return
    }
    wx.uploadFile({
      url: 'http://api.tanwancat.com/file/uploadaudio',
      filePath: self.data.tempFilePath,
      header: { "Content-Type": "multipart/form-data" },
      name: 'file',
      formData: {
        token: wx.getStorageSync('Cookie'),
      },
      suceess (res) {
        wx.showToast({
          icon: 'success',
          title: '上传成功'
        })
        self.setData({ audioSrc: app.fileUrl + res.url, audioIsSuccess: true });
      },
      fail (err) {
        wx.showToast({
          icon: 'error',
          title: '上传失败'
        })
      },
      complete: function (res) {
        console.log(res);
        let data = JSON.parse(res.data);
        if (data.code == 0) {
          self.setData({ audioSrc: data.data, audioIsSuccess: true });
          wx.showToast({
            icon: 'success',
            title: '上传成功',
            duration: 1000,
            success: function () {
              self.setData({
                soundRecordShow: false,
                audioIsSuccess: false,
                secondNum: 0
              })
            }
          })
        }
      },
    })
  },
  againAudio () {
    this.setData({
      secondNum: 0
    })
  },
  //录音
  recorderClick () {
    this.setData({
      soundRecordShow: true,
    })
  },
  endAudio () {
    let self = this;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      self.setData({ tempFilePath: res.tempFilePath })
      console.log('停止录音', res.tempFilePath);
      wx.uploadFile({
        url: 'http://api.tanwancat.com/file/uploadaudio',
        filePath: self.data.tempFilePath,
        header: {
          "Content-Type": "multipart/form-data"
        },
        name: 'file',
        formData: {
          skill_id: 1,
          token: wx.getStorageSync('Cookie'),
        },
        suceess (res) {
          console.log(res);
          self.setData({ audioSrc: res.url, audioIsSuccess: true });
        },

        fail (err) {
          console.log(err);
        },
        complete: function (res) {
          console.log(res);
          let data = res.data;

          if (data.code == 0) {
            self.setData({ audioSrc: data.url, audioIsSuccess: true });
          }
        },
      })
    })
  },
  playAudio () {
    innerAudioContext.src = this.data.tempFilePath
    innerAudioContext.autoplay = true
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })

  },

  //提交认证信息
  submitInfo () {
    if (!this.data.imgIsSuccess) {
      wx.showToast({
        title: '请上传资质图片',
        icon: 'loading',
        duration: 800,
      })
      return;
    }
    // if (!this.data.audioIsSuccess) {
    //   wx.showToast({
    //     title: '请上传语音',
    //     icon: 'loading',
    //     duration: 800,
    //   })
    //   return;
    // }
    // if (!this.data.grade) {
    //   wx.showToast({
    //     title: '请选择等级',
    //     icon: 'loading',
    //     duration: 800,
    //   })
    //   return;
    // }
    if (!this.data.setskillIntroduce) {
        wx.showToast({
            title: '请填写技能说明',
            icon: 'loading',
            duration: 800,
        })
        return;
    }
    if (this.data.setskillIntroduce == '') {
      this.setData({ skillIntroduceFlag: 0 })
      return
    }
    let json = {
      token: wx.getStorageSync('Cookie'),
      skill_id: this.data.skill.skill_id,
      level: this.data.grade,
      cover: this.data.imgSrc,
      audio: JSON.stringify({ url: this.data.audioSrc, duration: this.data.secondNum }),
      description: this.data.setskillIntroduce,
    }
    ajax('seller/applyemotion', json).then(res => {
      wx.showToast({
        title: '提交成功，请耐心等待',
        icon: 'success',
        image: '',
        duration: 1500,
        mask: true,
        success: function (res) {
          wx.redirectTo({
            url: '../review/review'
          })
        },
        fail: function (res) { },
        complete: function (res) { },
      })
    })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})